const Joi = require('@hapi/joi')

const schemaConfig = {
  allowUnknown: false,
  abortEarly: true
}

const schema = Joi.object({
  id: Joi.number()
    .sign('positive')
    .min(100000)
    .max(999999),
  baseName: Joi.string(),
  password: Joi.string(),
  access_token: [Joi.string().min(10), Joi.number().min(999)],
  base_sex: Joi.string()
    .valid('男', '女')
    .default('男'),
  base_age: Joi.number()
    .integer()
    .positive()
    .when('base_sex', {
      is: '男',
      then: Joi.number().max(100),
      otherwise: Joi.number().max(101)
    })
    .required(),
  remark: Joi.string()
    .min(10)
    .max(100)
    .default('not have remark'),
  location_time: Joi.date()
    .min('2000-1-1')
    .max('2022-1-1')
    .timestamp('javascript'),
  // javascript-milliseconds unix-seconds
  server_port: Joi.number()
    .port()
    .min(1000)
    .default(4546),
  base_type: Joi.valid('admin', 'user', 'people').default('people'),
  menus: Joi.array()
    .ordered(Joi.number().required())
    .items(Joi.string(), Joi.any().strip())
    .required()
})
  .rename('baseName', 'userName') // alias
  .and('baseName', 'password')
  .oxor('password', 'access_token')

let validateFn = validate => {
  let result = schema.validate(validate, schemaConfig)
  console.log(result)
}

let input = {
  // baseName: 'hahahah',
  // userName: 'hahahah', // alias
  // password: '%70%61%73%73%77%6f%72%64',
  remark: 'this is a remark ....',
  location_time: '1577433721899',
  access_token: '%70%61%73%73%77%6f%72%64',
  server_port: (1 << 16) - 1,
  // noKey: 'no', // => error
  menus: [1, 'HOME', 2, 'BOOK'], // => [1,'HOME','BOOK']
  base_sex: '女',
  base_age: 101
}

validateFn(input)
